import axios from 'axios'
import 'element-plus/es/components/message/style/css'
import { ElMessage } from 'element-plus'

let messageInstance = null

const openMessage = message => {
  if (!messageInstance) {
    messageInstance = ElMessage({
      message,
      type: 'error',
      duration: 3 * 1000,
      onClose: () => {
        messageInstance = null
      }
    })
  }
}

// 创建axios实例
const createRequest = () => {
  const instance = axios.create({
    baseURL: import.meta.env.VITE_BASE_URL,
    timeout: 60000 // request timeout
  })
  // request interceptor
  instance.interceptors.request.use(
    config => {
      return config
    },
    error => {
      // do something with request error
      console.log(error) // for debug
      return Promise.reject(error)
    }
  )

  // response interceptor
  instance.interceptors.response.use(
    response => {
      // 暂时返回response.data，注意后台返回文件流时的结果
      return response.data
    },
    error => {
      const { status, data } = error.response
      switch (status) {
        case 400:
          openMessage(data.msg)
          break
        case 401:
          openMessage('登录失效，请重新登录')
          break
        case 500:
        case 502:
          openMessage('服务器错误！')
          break
        case 504:
          openMessage('服务器内部连接超时！')
          break
        default:
          openMessage(data.message)

          break
      }
      return Promise.reject(error)
    }
  )
  return instance
}

const service = createRequest()

const post = (url, parameter) => {
  return service({
    url: url,
    method: 'post',
    data: parameter
  })
}
const get = (url, parameter) => {
  return service({
    url: url,
    method: 'get',
    params: parameter
  })
}

export { post, get }
